# -*- coding: utf-8 -*-
"""
Created on 2022
@author: GLTS
"""
import requests
from requests.exceptions import RequestException
import tkinter as tk


def fanyi():
    original_str = in_put.get(0.0, 'end')  # 定义一个变量，用来接收输入框输入的值
    data = {
        'doctype': 'json',
        'type': 'AUTO',
        'i': original_str  # 将输入框输入的值，赋给接口参数
    }
    url = "http://fanyi.youdao.com/translate"
    try:
        r = requests.get(url, params=data)
        if r.status_code == 200:
            result = r.json()
            translate_result = result['translateResult'][0][0]["tgt"]
            in_fo.delete(1.0, "end")  # 输出翻译内容前，先清空输出框的内容
            in_fo.insert('end', translate_result)  # 将翻译结果添加到输出框中
    except RequestException:
        in_fo.insert('end', "发生错误")
    except KeyError:
        in_fo.delete(0.0, "end")
        in_fo.insert('end', "错误:未输入内容")


window = tk.Tk()
window.title('翻译器')
window.geometry('940x300')
window.geometry('+240+220')
window.resizable(False, False)

# "翻译内容"框子
labelframe = tk.LabelFrame(width=430, height=200, text="翻译内容", font=('', 11))
labelframe.grid(column=0, row=0, padx=20, pady=10)
# 输入框
in_put = tk.Text(window, font=('', 13))
in_put.place(x=38, y=35, width=392, height=157)
# "翻译结果"框子
labelframe2 = tk.LabelFrame(width=430, height=200, text="翻译结果", font=('', 11))
labelframe2.grid(column=1, row=0, padx=20, pady=10)
# 输出框
in_fo = tk.Text(window, font=('', 13))
in_fo.place(x=509, y=35, width=392, height=157)
# '翻译'按钮
t_button = tk.Button(window, text='  翻 译  ', font=('', 15), relief=tk.GROOVE, command=fanyi)
t_button.place(x=785, y=237)

window.mainloop()
